package com.weex.app.extend;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.os.Process;
import android.support.v7.app.AlertDialog;
import android.util.SparseArray;

import com.taobao.weex.WXSDKEngine;
import com.taobao.weex.annotation.JSMethod;
import com.taobao.weex.bridge.JSCallback;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;


public class Permission extends WXSDKEngine.DestroyableModule {
    private JSCallback _opened;
    
    @JSMethod(uiThread=false)
    public void open(String setting,JSCallback callback) {
        Intent intent = new Intent(setting);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        ((Activity) mWXSDKInstance.getContext()).startActivityForResult(intent, 1);
        _opened=callback;
    }
    
    @Override
    public void destroy() {
    }

    @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
        _opened.invoke(requestCode);
        _opened=null;
    }
    
   
    @JSMethod(uiThread=false)
    public void has(String setting, JSCallback callback) {
        PackageManager packageManager = mWXSDKInstance.getContext().getPackageManager();
//        Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
        Intent intent = new Intent(setting);

        List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
                PackageManager.MATCH_DEFAULT_ONLY);
        callback.invoke( list.size() > 0 );
    }

//    private SparseArray<JSCallback> callbacks;
//    private static AtomicInteger codeGenerator = new AtomicInteger(100);

/*
    @JSMethod(uiThread=false)
    public void check(String permission, JSCallback callback) {
        boolean granted = false;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            granted = mWXSDKInstance.getContext().checkPermission(permission, Process.myPid(), Process.myUid())
                    == PackageManager.PERMISSION_GRANTED;
        } else {
            granted = mWXSDKInstance.getContext().checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
        }
        callback.invoke(new SimplePermissionResult(permission, granted, States.SUCCESS, null));
    }

    @JSMethod(uiThread=false)
    public void request(final String permission, Map<String, String> rationale, final JSCallback callback) {
        final Context context = mWXSDKInstance.getContext();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            boolean ret = context.checkPermission(permission, Process.myPid(), Process.myUid()) ==
                    PackageManager.PERMISSION_GRANTED;
            callback.invoke(new SimplePermissionResult(permission, ret, States.SUCCESS, null));
            return;
        } else if (context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) {
            callback.invoke(new SimplePermissionResult(permission, true, States.SUCCESS, null));
            return;
        }

        if (context instanceof Activity) {
            if (shouldShowRequestPermissionRationale((Activity) context, permission)) {
                if (rationale != null && rationale.size() > 0) {
                    AlertDialog dialog = new AlertDialog.Builder(context)
                            .setTitle(rationale.get("title"))
                            .setMessage(rationale.get("message"))
                            .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    callback.invoke(new SimplePermissionResult(permission, false, States.CANCEL, "request canceled"));
                                }
                            })
                            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    requestPermissionInner(context, permission, callback);
                                }
                            })
                            .create();
                    dialog.setCanceledOnTouchOutside(false);
                    dialog.show();
                } else {
                    requestPermissionInner(context, permission, callback);
                }
            } else {
                requestPermissionInner(context, permission, callback);
            }
        } else {
            callback.invoke(new SimplePermissionResult(permission, false, States.FAILED, context.toString() + " is not an Activity"));
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        onRequestPermissionsResultInner(requestCode, permissions, grantResults);
    }

    private void requestPermissionInner(Context context, String permission, JSCallback callback) {
        try {
            int requestCode = codeGenerator.getAndIncrement();
            callbacks.put(requestCode, callback);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                ((Activity) context).requestPermissions(new String[]{permission}, requestCode);
            } else {
                callback.invoke(new SimplePermissionResult(permission, false, States.FAILED, "SDK version code less than 23"));
            }
        } catch (Exception e) {
            callback.invoke(new SimplePermissionResult(permission, false, States.FAILED, e.toString()));
            e.printStackTrace();
        }
    }

    private boolean shouldShowRequestPermissionRationale(Activity activity, String permission) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return false;
        } else {
            return activity.shouldShowRequestPermissionRationale(permission);
        }
    }

    private void onRequestPermissionsResultInner(int requestCode, String[] permissions, int[] grantResults) {
        JSCallback callback = callbacks.get(requestCode);
        if (callback != null) {
            callback.invoke(new SimplePermissionResult(permissions[0], grantResults[0] == PackageManager.PERMISSION_GRANTED, States.SUCCESS, null));
        }
        callbacks.remove(requestCode);
    }



    private class SimplePermissionResult extends HashMap<String, Object> {
        SimplePermissionResult(String permission, boolean granted, String reason, String message) {
            super(4);
            put("permission", permission);
            put("granted", granted);
            put("state", reason);
            put("message", message);
        }
    }

    interface States {
        String SUCCESS = "success";
        String FAILED = "failed";
        String CANCEL = "cancel";
    }
*/
}
